/**
 * 浏览历史记录 description:20160514文件路径整合时没发现被引用，暂时留存，以防万一【李加良】
 */
var browseHistory,currentProduct,SEPERATOR,count,productIds,historylen,cat,hisCount,myHistory= "";
var skus,hisSkus= [];
FourPage.showMyHistory = function(){
	try{
		browseHistory = FourPage.getCookieBonus("smhst"); // 取得COOKIES
	    currentProduct = (sn.partNumber).substring(9,18);
		SEPERATOR = "a";
		count = 1;
		hisCount = 0;
		productIds = FourPage.updateHistory(browseHistory,currentProduct,SEPERATOR); // 更新cookies文件，并返回cookies历史商品ID
		historylen ;           // cookies中商品个数
		if(productIds == null || (productIds.length ==1 && currentProduct == productIds[0]))
		{
			historylen = 1;
			productIds = [];
			productIds[0] = currentProduct;
			skus = productIds;
		}
		else
		{
			skus = [];
			historylen = productIds.length;
			var a = 0;
			//当前商品编码放第一个
			$.each(productIds,function(i,sku){
				if(sku != currentProduct){
					skus[a+1] = sku;
					a++;
				}
			});
			skus[0] = currentProduct;
			historylen++;
		}
		myHistory = '<h3>最近浏览</h3><div class="scroll-box"><ul>';
		historylen = historylen>=6?6:historylen;//存8取6
		FourPage.mysetHistoryValue(skus,count,sn.cityId,sn.imageDomianDir,sn.storeId,sn.catalogId,'-7',historylen);
		var tuijianHis = [];
		if(skus.length>4){
			for(var i=0;i<4;i++){
				tuijianHis[i] = skus[i];
			}
		}else{
			tuijianHis = skus;
		}
		//根据您的浏览猜您喜欢
		CommonFourPage.Recommend.historyRec(tuijianHis,"Recommend.historyRecHtml");
	}catch(e){}
};

//监控代码
function setiDiggerTrackingCodes(){
	var categoryids="";
    if(typeof sn.category1!='undefined'){
    	categoryids = sn.category1;
    }
    if(typeof sn.category2!='undefined'){
    	categoryids += '_'+sn.category2;
    }
    if(typeof sn.categoryId!='undefined'){
    	categoryids += '_'+sn.categoryId;
    }
    iDiggerTrackingCodes(sn.partNumber,categoryids,_wmmq);
}

/**
 * 更新浏览历史的cookie
 */
FourPage.updateHistory = function(browseHistory,currentProduct,SEPERATOR){
    try{
    	var browseHistoryArray;
        var newHistory;	
        if(FourPage.isNotEmpty(currentProduct)){
    	   if(FourPage.isNotEmpty(browseHistory)){  
    		   // 浏览历史不为空
    	       if(browseHistory.indexOf(currentProduct)<0){   
    	    	   // 浏览历史不包含当前浏览商品
    	           browseHistoryArray = browseHistory.split(SEPERATOR);
    	           if(browseHistoryArray.length<8){      
    	        	    // 浏览历史不足8个
    	                newHistory =currentProduct+SEPERATOR+browseHistory;
    	           }else{                              
    	        	   // 浏览历史满足8个	               
    	               newHistory = currentProduct+SEPERATOR+browseHistory.substring(0,browseHistory.lastIndexOf(SEPERATOR));
    	           }	           
    	           // 浏览历史包含当前商品
    	       }else{
    	           return browseHistory.split(SEPERATOR);  
    	       }
    	   // 浏览历史为空
    	   }else{
    	       newHistory = currentProduct;
    	   }
    	   // 更新浏览历史
    	   FourPage.setCookieBonus("smhst",newHistory,30);
    	   if( browseHistory == null )
    	   {
    	  	 return newHistory.split(SEPERATOR);
    	   }
    	   else 
    	   {
    	  	 return browseHistory.split(SEPERATOR);
    	   }
    	}else{
    	   return browseHistory==null?null:browseHistory.split(SEPERATOR);
    	}
    }catch(e){}
};

/**
 * 判断是否为空
 */
FourPage.isNotEmpty = function(obj) {
	return obj != null && $.trim(obj).length > 0;
};

/**
 * 读取COOKIES
 */
FourPage.getCookieBonus = function(key){    
	var arrStr = document.cookie.split(";");
	for(var i = 0; i < arrStr.length; i++){
		var temp = arrStr[i].split("=");
		if($.trim(temp[0]) == key){
			return temp[1];
		}
	}
	return null;	
};

/**
 * 写入cookies
 */
FourPage.setCookieBonus = function(key,val,lifecycle){
	var ExpireDate = new Date();
	ExpireDate.setTime(ExpireDate.getTime() + (lifecycle*1000*3600*24)); // 设置有效期为lifecycle天
	document.cookie = key + "=" + val +
	((lifecycle == null) ? "" : "; expires=" + ExpireDate.toGMTString())+";path=/;domain="+sn.cookieDomain;	
};

/**
 * 获取浏览历史记录
 */
FourPage.mysetHistoryValue = function(skus,count,cityId,imageDomain,storeId,catalogId,langId,historylen){
	cat = skus[count-1];
	var url = "http://"+sn.domain+sn.context+"/bHistory_10052_"+catalogId+"_"+cat+"_"+cityId+"_FourPage.histroyHtml_.html";
	$.ajax({
	    url:url,
	    cache: true,
	    dataType: 'jsonp',
		jsonp:"callback",
		jsonpCallback: "histroyHtml",
	    success: function(response){
	     }
	  });
};

/**
 * 浏览历史回调
 */
FourPage.histroyHtml = function(response){
	try{
		if(response !=null && response.price!=""){
			myHistory += '<li sku="'+cat+'"><a name="item_'+sn.ninePartNumber+'_llls_pic0'+count+'" target="_blank" href="'+sn.elecProductDomain+'/'+cat+'.html"><img alt="'+response.name+'" src="'+sn.imageDomianDir+'/b2c/catentries/000000000'+cat+'_1_60x60.jpg"/></a><p class="title"><a name="item_'+sn.ninePartNumber+'_llls_word0'+count+'" target="_blank" href="'+sn.elecProductDomain+'/'+cat+'.html">'+response.name+'</a></p><p class="price"><i>&yen;</i>'+(response.price==""?"":parseFloat(response.price).toFixed(2))+'</p></li>';
			hisSkus[hisCount] = cat;
			hisCount ++;
		}
	    if(count < skus.length && count <6){
	    	count = count + 1;
	    	FourPage.mysetHistoryValue(skus,count,sn.cityId,sn.imageDomain,sn.storeId,sn.catalogId,'-7',historylen);
	    }else{
	    	myHistory += '</ul></div>';
	    	myHistory +='<div class="scroll-handle"><a class="btn-dir prev" href="javascript:void(0);"></a><a class="btn-dir next" href="javascript:void(0);"></a></div>';
	    	$("#J-historyList").html(myHistory);
	    	if(hisCount ==0){//有价格的浏览历史
	    		$(".history").parent().hide();
	    	}else{
	    		$(".history").parent().show();
	    	}
	    	if($("#J-historyList").find("li").length>3){
	    		// 历史记录
		        iFourth.listloop({
		            wrap: '#J-historyList',
		            loopBox: '.scroll-box ul',
		            step: { wide: 3, narrow: 3},
		            scrollWidth: { wide: 270, narrow: 270},
		            vertical: true,
		            isLoop: false
		        });
	    	}else{
	    		$("#J-historyList").find(".scroll-handle").hide();
	    	}
	    }
	}catch(e){}
};



/*
 * 返回到首页，并激活合适的Tab页展示
 * 
 * goToTab所传入的值。  action：行动； success：战绩； mine:我的；
 */
function goBackIndex(userId, goToTab, deviceId) {
    window.location.href= basePath + "/menu/index?userId=" + userId + "&activeTab="+ goToTab + "&deviceId=" + deviceId;
}


/*文本框提示文字组件 */
/*******************/

function inputPrompt(){
    var input = $('input[prompt]');
    var input_l = input.length;
    input.map(function(){
        var input_prompt = $(this).attr('prompt');
        var input_prompt_color = $(this).attr('promptcolor');
        if ($(this).val() == '') {
            $(this).val(input_prompt).css({color:input_prompt_color});
        }
        
        $(this).on('focus',function(){
            var input_val = $(this).val();
            if (input_val == input_prompt) {
                $(this).val('').css({color:''});
            }
        });
        
        $(this).on('blur',function(){
            var input_val = $(this).val();
            if (input_val == '') {
                $(this).val(input_prompt).css({color:input_prompt_color});
            }
        });
    }); 
}


;(function(){
    //复选框
    function checkbox(setting){
        var setting = setting || {};
        var $query = setting.query || 'body';
        if (setting.click_ele!=undefined){
            var $btn_click =  $(setting.click_ele,$query);
        } else {
            var $btn_click =  $('.btn_sel',$query);
        }
        
        var checkbox = $('.btn_sel',$query);
        var $selfun = setting.selfun || function(){};
        var $removefun = setting.removefun || function(){};
        $btn_click.on('click',function(){
            if (setting.click_ele!=undefined){
                var $target_ele = $('.btn_sel',this);
            } else {
                var $target_ele = $(this);
            }
            
            if ($target_ele.hasClass('btn_sel_sel')) {
                $target_ele.removeClass('btn_sel_sel');
            } else {
                $target_ele.addClass('btn_sel_sel');
            }
            if (typeof($selfun) == 'function') {
                $selfun.apply($target_ele);
            }
            if (typeof($removefun) == 'function') {
                $removefun.apply($target_ele);
            }
        });
    }
    
    //单选框
    function rediobox(setting){
        var setting = setting || {};
        var $query = setting.query || 'body';
        if (setting.click_ele!=undefined){
            var $btn_click =  $(setting.click_ele,$query);
        } else {
            var $btn_click =  $('.redio_sel',$query);
        }
        
        var rediobox = $('.redio_sel',$query);
        var $selfun = setting.selfun || function(){};
        var $removefun = setting.removefun || function(){};
        $btn_click.on('click',function(){
            if (setting.click_ele!=undefined){
                var $target_ele = $('.redio_sel',this);
            } else {
                var $target_ele = $(this);
            }
            
            if (!$target_ele.hasClass('redio_sel_sel')) {
                $('.redio_sel',$query).removeClass('redio_sel_sel');
                $target_ele.addClass('redio_sel_sel');
            }
            if (typeof($selfun) == 'function') {
                $selfun.apply();
            }
            if (typeof($removefun) == 'function') {
                $removefun.apply();
            }
        });
    }
    
    window.rediobox = rediobox;
    window.checkbox = checkbox;
})();

/*弹框*/
;(function(){

    function openPop(settings){
    	
        if (!settings.url && !settings.target && !settings.text) {
            return false;
        }
        
        createPop();
        $('.pop_box_content','#pop_box').css({'overflow-y':'visible','height':'auto'});
        
        if (settings.url){
            $('.pop_box_content','#pop_box').load(settings.url,function(){
                successPop(settings);
            });
            
            return true;
        }
        
        if (settings.target){
            var $nr_html = $('#'+settings.target).html();
            $('.pop_box_content','#pop_box').html($nr_html);
            successPop(settings);
            return true;
            
        }
        
        if (settings.text){
            $('.pop_box_content','#pop_box').html('<h2 class="a-center">'+settings.text+'</h2>');
            successPop(settings);
        }
    }
    
    function successPop(settings) {
        $('.pop_mask').css({'display':'block'});
        var pop_h = $('.pop_box_content').height();
        var page_h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        var t_h = $('.pop_box_header').height();
        var f_h = $('.pop_box_footer').height();
        var scroll_h = 0;
        
        var $title_text = settings.title ? settings.title : '提示框'; 
        $('.pop_box_header_text','#pop_box').html($title_text);
        
        if (settings.btn) {
        	var $btn_style = settings.btn.style ? settings.btn.style : 'btn_blue';
            var $btn_t = '<a class="<{style}> b4_5 w90 f24 mt10 confirm_btn" href="javascript:void(0)"><{template}></a>';
            
            $btn_t = $btn_t.replace('<{style}>',$btn_style);
            if (settings.btn.name) {
                $btn_t = $btn_t.replace('<{template}>',settings.btn.name);
            } else {
                $btn_t = $btn_t.replace('<{template}>','确 定');
            }
            
            $('.pop_box_footer','#pop_box').html($btn_t);
            $('.pop_box_footer','#pop_box').show();
            
            $('.confirm_btn','#pop_box').on('click',function(){
                if (settings.btn.fun && typeof(settings.btn.fun) == 'function') {
                    settings.btn.fun.apply();
                } else {
                    closePop(settings);
                }
                
            });
        } else {
            $('.pop_box_footer','#pop_box').hide();
            f_h = 0;
        }
        
        scroll_h = page_h-100-t_h-f_h;
        if (pop_h>scroll_h) {
            $('.pop_box_content').css({'overflow-y':'auto','height':scroll_h+'px'});
            pop_h = scroll_h+t_h+f_h;
        } else {
            $('.pop_box_content').css({'overflow-y':'visible','height':pop_h+'px'});
            pop_h = pop_h+t_h+f_h;
            
        }
        
        $('.pop_box').animate({'height':pop_h+'px'});
        $('.close_pop','#pop_box').on('click',function(){
            closePop(settings);
        });
        if (settings.openfun!=undefined && typeof(settings.openfun) == 'function') {
            settings.openfun.apply();
        }
    }
    
    function closePop(settings){
        settings = settings || {};
        $('#pop_mask').css({'display':'none'});
        $('.pop_box_header_text','#pop_box').html('');
        $('.pop_box_content','#pop_box').html('');
        $('.pop_box_footer','#pop_box').html('');
        $('.pop_box').css({'height':'0px'});
        if (settings.closefun!=undefined && typeof(settings.closefun) == 'function') {
            settings.closefun.apply();
        }
    }
    
    function createPop(){
        var $pop = $('#pop_box');
        if ($pop.length > 0) {
            return false;
        }
        var $pophtml = '<div class="pop_mask lp60" id="pop_mask"></div>';
        $pophtml = $pophtml + '<div class="pop_box" id="pop_box">';
        $pophtml = $pophtml + '<div class="pop_box_div">';
        $pophtml = $pophtml + '<div class="pop_box_html"><div class="pop_box_header"><div class="pop_box_header_text"></div>'
        $pophtml = $pophtml + '<a href="javascript:void(0)" class="btn_close close_pop"></a></div>';
        $pophtml = $pophtml + '<div class="pop_box_content"></div><div class="pop_box_footer"></div></div>'; 
        $pophtml = $pophtml + '</div>';
        $pophtml = $pophtml + '</div>';
        $pophtml = $pophtml + '</div>';
        $('body').append($pophtml);
    }
    
    //提示框
    var promptTimer= '';
    function promptPop(settings){
        
        if (!settings.text) {
            return false;
        }
        
        if (promptTimer != '') {
            clearTimeout(promptTimer);
        }
        _createPrompt();
        
        $('#pop_prompt_html').html(settings.text);
        $('#pop_prompt').css({'display':'block','top':'70%','opacity':'1'});
        $h= $('.pop_prompt_div','#pop_prompt').height();
        $('.pop_prompt_mode','#pop_prompt').css({'height':$h+'px'});
        $('.pop_prompt_div','#pop_prompt').css({'margin-top':-1*$h+'px'});
        $('#pop_prompt').attr('class','pop_prompt pop_prompt_show');
        
        promptTimer = setTimeout(function(){
            $('#pop_prompt').attr('class','pop_prompt');
            $('#pop_prompt').animate({'opacity':'0.1'},500,function(){
                $('#pop_prompt_html').html('');
                $(this).css({'display':'none'});
                if (settings.closefun!=undefined && typeof(settings.closefun) == 'function') {
                	settings.closefun.apply();
                }
            });
        },1000);
    }
    
    function _createPrompt(){
        var $prompt = $('#pop_prompt');
        if ($prompt.length > 0) {
            return false;
        }
        $pophtml = '<div class="pop_prompt" id="pop_prompt"><div class="pop_prompt_mode lp60 b4_5"></div><div class="pop_prompt_div pos_r"><div class="p10 color_white" id="pop_prompt_html"></div></div></div>';
        $('body').append($pophtml);
    }
    
    window.openPop = openPop;
    window.closePop = closePop;
    
    window.promptPop = promptPop;
})();

/* 倒计时 */
;(function(){
		  
    //格式化时间
    /*type 样式*/
    /*2 去除天数 小时 显示 分秒
    /*3 >1 day 5天 ; <1 day 15:41:49
    /*4 >1 day 1天01小时06分12秒;  <1 day 显示 15小时40分05秒*/
    /*其他 >1 day 35:41:49 ; <1 day 15:41:49
    /*********************/
    
    $.fn.countDown = function(startTime,endTime,type,fun){
    	if(startTime>=endTime){
            this.text("00:00:00");
            return false;
        }
        var startTime1 = startTime *1/1000;
        var endTime1 = endTime *1/1000;
        var _this = this
        var timer = setInterval(function(){
                startTime1 = startTime1*1+1;
                var aTime = endTime1 - startTime1;
                if(aTime<=0){
                        clearInterval(timer);
                        if(fun && typeof(fun)=='function'){
                        	fun.apply();
                        }
                }
                var newTime = formatTime(aTime,type);
                _this.text(newTime);
        },1000);
            
    }
    
    function formatTime(aTime, type) {
            if(type==3 || type == 4){
                    var ta = [24*60*60, 60*60 , 60, 1];
                    var tb = [4];
            }else{
                    var ta = [60*60 , 60, 1];
                    var tb = [3];
            }
            var i;
            if (aTime > 0) {
                    for(i=0;i<=ta.length;i++) {
                            tb[i]=Math.floor( aTime / ta[i] );
                            aTime = aTime % ta[i];
                    }
                    if (type == 2) {
                            return (_zero(tb[1])+":"+_zero(tb[2]));
                    } else if(type == 3){
                            if(tb[0]>0){
                                    return tb[0]+"天";
                            }else{
                                if (_zero(tb[1])*1==0) {
                                    return (_zero(tb[2])+":"+_zero(tb[3]));
                                } else {
                                    return (_zero(tb[1])+":"+_zero(tb[2])+":"+_zero(tb[3]));
                                }
                            }
                    } else if (type == 4) {
                            if (tb[0]>0){
                                    return tb[0] + "天" + (_zero(tb[1]) + "小时" +_zero(tb[2]) +"分" +_zero(tb[3])) + "秒";
                            }else{
                                    return (_zero(tb[1]) + "小时" +_zero(tb[2]) +"分" +_zero(tb[3])) + "秒";
                            }
                    } else {
                            return (_zero(tb[0])+":"+_zero(tb[1])+":"+_zero(tb[2]));
                    }
            } else {
                    return '00:00:00';
            }
    }
    
    function _zero(time) {
            if(time <= 9) {
                    return '0' + time;
            } else { 
                    return time;
            } 
    }
	
    window.formatTime = formatTime;

})();

(function($){
	// ajax 请求 Edited By Edward 2014-10-21
	$.postajax=function(url,data,successfn,arg){
		$("#loadImg").css("visibility","visible");
		$("#clickMore").text("正在加载中").css("color","#0b7cca");
		$.ajax({
		    url:url,
		    async:false,
		    type:'post',
		    data:data || {},
		    dataType:"json",
			timeout:5000,
			error : function handleAjaxError(xhr, textStatus, error) {
				if (textStatus === "timeout") {
					//comAlertObj("连接超时!请稍后再试");
				} else if (textStatus == "error") {
					//comAlertObj("系统繁忙,请稍后再试");
				}
			},
		    success : function(data) {
		    	$("#loadImg").css("visibility","hidden");
		    	$("#clickMore").text("点击加载更多").css("color","#333");
		    	successfn.call(this,data,arg);
		    }
		});
	};
	
	(function($){
		// 仿制 jquery slideUp slideDown 效果  Edited By Edward 2014-10-21
		$.fn.slideUp = function(time){
			var height = this.height(),time=time||80,step=50,_this=this,num=height;
			var timer = setInterval(function(){
				height-=step;
				if(height<=0){
					height=0;
					_this.css({
						"display":"none",
						"height":"auto"
					});
					clearInterval(timer);
				}else{
					_this.height(height);
				}
			},time);
		};
		$.fn.slideDown = function(time){
			var time = time||80,step=50,num=0,_this=this,height=0;
			if(this.css("display")=="none"){
				height = this.getRealHeight();
				this.css({
					"height":0,
					"display":"block"
				});
			}
			var timer = setInterval(function(){
				num+=step;
				if(num>=height){
					num=height;
					clearInterval(timer);
					$.isAnimate = true;
				}
				_this.height(num);
			},time);
		}
		$.fn.getRealHeight = function(){
			var height = 0;
			if(this.css("display")=="none"){
				this.css({
					"display":"block",
					"visibility":"hidden"
				});
			}
			height = this.height();
			this.css({
				"display":"none",
				"visibility":"visible"
			});
			return height;
		}	
	})($);
	 
	;(function($){
		// 千分位效果  Edited By Edward  2014-10-22
		function formatPrice(point){
			if(this.length==0){return false;}
			var number = 0,isInputObj = null,toLower=this[0].tagName.toLowerCase(),_this = this;
			if(toLower=="input" || toLower=="textarea"){
				// input || textarea dom;
				isInputObj = true;
				comdify(this.val().replace(/,/g,""));
			}else{
				// text dom;
				isInputObj = false;
				comdify(this.text().replace(/,/g,""));
			}
			function comdify(n){
				// format;
				if(point){
					n = (n*1).toFixed(point);
				}
				var re=/\d{1,3}(?=(\d{3})+$)/g;
				var n1=n.replace(/^(\d+)((\.\d+)?)$/,function(s,s1,s2){return s1.replace(re,"$&,")+s2;});
				// 报错规避
				if(!n1){return _this.val()}
				if(isInputObj){
					// input || textarea dom;
					_this.val(n1);
				}else{
					// text dom;
					_this.text(n1);
				}
			}
		}
		$.fn.formatPrice = formatPrice;
	})($);
	
	;(function($){
		// 手机号码格式化  Edited By Edward  2014-10-22
		function telFormat(){
			if(this.length==0){return false;}
			var value = this.text().replace(/^(\d{3})\d{4}(\d{4})$/,"$1****$2");
			return this.text(value);
		}
		$.fn.telFormat = telFormat;
	})($);
	
	;(function($){
        // click 点击获取更多公用方法  Edited By Edward 2014-10-24
        function clickMore(obj,ajaxData,callBack,flag){
            var len = obj.find(".pageItemFlag").length;			// 当前页面可见数据条数
            var currentPageNum = ajaxData.data.currentPage || 1;// 当前数据第几页
            var pageSizeNum = ajaxData.data.pageSize || 10;		// 每页显示10条数据
            var _this = this;
            function clickMoreFn(){
                _this.click(function(){
                	ajaxData.data.currentPage = currentPageNum;
                    loadMoreList(obj,ajaxData,callBack,flag);
                });   
                function loadMoreList(listIdObj,ajaxData,callBack,flag) {
                    $("#loadImg").css("visibility","visible");
                    $.ajax({
                        type: "POST",
                        url: ajaxData.url,
                        data:ajaxData.data,                  // ajax 的参数
                        success: function(data){
                            $("#loadImg").css("visibility","hide");
                            if(flag){                       // dom结构 ul包含include数据
                                listIdObj.append(data);
                            }else{                          // dom结构 为div包含数据
                                _this.before(data);
                            }
                            len = obj.find(".pageItemFlag").length;
                            if(len < currentPageNum * pageSizeNum){// 判断是否还有数据
                                _this.css("display","none");
                            }
                            currentPageNum++;				// 当前页累加
                            if(callBack){callBack(currentPageNum)}
                        }
                    });
                }
            }
            return {                    
                init:function(){
                    if(len>=pageSizeNum){
                        clickMoreFn();
                    }else{
                        _this.css("display","none");
                    }
                }
            }         
        }
        $.fn.clickMore = clickMore;
    })($);
})($);



